#!python3
# 文件名：server.py

import socket
import time
import sys

ENCODING = 'utf-8'
BUFFER_SIZE = 1024

# 创建 socket 对象: socket.socket([family[, type[, proto]]])
#   family: 套接字家族可以是 AF_UNIX 或者 AF_INET
#   type: 套接字类型可以根据是面向连接的还是非连接分为SOCK_STREAM或SOCK_DGRAM
#   protocol: 一般不填默认为0
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 加入socket配置，重用ip和端口
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# 绑定ip端口号
serverSocket.bind(('localhost', 9999))

# 设置最大链接数，超过后排队
serverSocket.listen(5)

while True:
    print("服务器启动，监听客户端消息")
    conn, address = serverSocket.accept()

    print("请求的客户端为：", address)
    while True:
        # 关闭编译器中代码检测中有关检测 Exception 的选项
        # noinspection PyBroadException
        try:
            request = conn.recv(BUFFER_SIZE)  # 读取客户端发送的消息

            print("客户端发送的消息为:", request.decode(ENCODING))

            if not request:
                break
            else:
                response = '我是一个时间戳服务器，现在是[%s]' % time.strftime("%Y-%m-%d %X")
                print("服务端返回的消息为:", response)
                conn.send(response.encode(ENCODING))  # 返回消息给客户端

        except Exception as exc:
            print("客户端连接已断开：", address)
            break
    conn.close()  # 关闭客户端链接
serverSocket.closel()
